/**
 * 专门用来处理房间相关的接口
 */

const express = require('express')
const util = require('util')
const roomRouter = express.Router()
const {
  selectRoomParticipantsSql,
  deleteRoomParticipantsTableSql,
  selectRoomChatSql,
  selectRoomChatLastSql,
  selectRoomInfoTableMaxSql,
  generateUpdateRoomInfoTableSql,
  selectRoleSql,
  insertRoomInfoTableSql,
  selectmIdByIsMeetingOnSql,
  selectRoomChatByTimeSql
} = require('../sql/roomGroup')

const { selectUser } = require('../sql/auth')
// 引入 db 文件
const { db } = require('../utils/db')

// 将db.query转换为返回Promise的函数
const queryPromise = util.promisify(db.query).bind(db)

// 获取房间内人员信息
roomRouter.get('/room/getParticipants', async (req, res) => {
  try {
    // 解构出roomId
    const { roomId } = req.query
    // 查询用户信息
    const participants = await queryPromise(selectRoomParticipantsSql, [
      parseInt(roomId)
    ])
    res.status(200).json({
      code: 200,
      msg: '获取信息成功',
      data: {
        participants
      }
    })
  } catch (error) {
    console.log(error)
    res.status(500).json({ error: '获取失败' })
  }
})

// 删除房间内某一个人
roomRouter.delete('/room/deleteParticipants', async (req, res) => {
  try {
    // 解构出roomId和account
    const { roomId, account } = req.query
    // 查询用户信息
    await queryPromise(deleteRoomParticipantsTableSql, [
      parseInt(roomId),
      account,
      account
    ])
    res.status(200).json({
      code: 200,
      msg: '删除成功',
      data: {}
    })
  } catch (error) {
    console.log(error)
    res.status(500).json({ error: '删除失败' })
  }
})

// 获取房间内聊天记录
roomRouter.get('/room/getChat', async (req, res) => {
  try {
    // 解构出roomId
    const { roomId } = req.query
    // 查询房间内聊天记录
    const chats = await queryPromise(selectRoomChatSql, [parseInt(roomId)])
    res.status(200).json({
      code: 200,
      msg: '获取信息成功',
      data: {
        chats
      }
    })
  } catch (error) {
    console.log(error)
    res.status(500).json({ error: '获取失败' })
  }
})

// 获取房间内最后一条聊天记录
roomRouter.get('/room/getChatLast', async (req, res) => {
  try {
    // 解构出roomId
    const { roomId } = req.query
    // 查询房间内聊天记录
    const chats = await queryPromise(selectRoomChatLastSql, [parseInt(roomId)])
    res.status(200).json({
      code: 200,
      msg: '获取信息成功',
      data: {
        chats
      }
    })
  } catch (error) {
    console.log(error)
    res.status(500).json({ error: '获取失败' })
  }
})

// 修改房间信息表的标题，密码
roomRouter.put('/room/putRoomInfo', async (req, res) => {
  try {
    const { roomId } = req.body
    if (!roomId) {
      return res.status(400).json({ error: 'roomId是必传参数' })
    }

    const fieldMappings = {
      title: req.body.title,
      password: req.body.password,
      endTime: req.body.endTime,
      isMeetingOn: req.body.isMeetingOn
    }

    // 过滤掉未定义的字段
    const filteredFieldMappings = Object.fromEntries(
      Object.entries(fieldMappings).filter(([, value]) => value !== undefined)
    )

    // 获取更新 SQL 语句
    const updateRoomInfoTableSql = generateUpdateRoomInfoTableSql(
      roomId,
      filteredFieldMappings
    )

    // 创建值数组，用于 SQL 语句中的参数替换
    const values = [...Object.values(filteredFieldMappings), parseInt(roomId)]

    // 执行 SQL 更新操作
    await queryPromise(updateRoomInfoTableSql, values)
    res.status(200).json({
      code: 200,
      msg: '更新成功',
      data: {}
    })
  } catch (error) {
    console.log(error)
    res.status(500).json({ error: '更新失败' })
  }
})

// 创建房间
roomRouter.post('/room/createRoom', async (req, res) => {
  try {
    const { roomId, account, title, capacity, password } = req.body
    // 根据用户的房间id去查询用户的等级
    const user = await queryPromise(selectUser, [account, account])
    const user_role = user[0].user_role
    // 根据用户的等级去查询对应的权限
    const role = await queryPromise(selectRoleSql, [user_role])
    const { timeMax: r_timeMax, capacity: r_capacity } = role[0]
    // In Progress || Completed
    const isMeetingOn = 'In Progress'
    // 创建对应的房间
    await queryPromise(insertRoomInfoTableSql, [
      parseInt(roomId),
      parseInt(roomId),
      account,
      title,
      capacity === 0 ? r_capacity : capacity,
      r_timeMax,
      password,
      isMeetingOn
    ])
    res.status(200).json({
      code: 200,
      msg: '创建成功',
      data: {}
    })
  } catch (error) {
    console.log(error)
    res.status(500).json({ error: '创建失败' })
  }
})

// 根据isMeetingOn的状态去查询现在是哪一个会议
roomRouter.get('/room/getRoomInfo', async (req, res) => {
  try {
    const { roomId } = req.query
    const roomInfo = await queryPromise(selectmIdByIsMeetingOnSql, [
      parseInt(roomId)
    ])
    res.status(200).json({
      code: 200,
      msg: '获取信息成功',
      data: {
        roomInfo
      }
    })
  } catch (error) {
    console.log(error)
    res.status(500).json({ error: '获取失败' })
  }
})

// 查询房间信息
roomRouter.get('/room/getRecordInfo', async (req, res) => {
  try {
    // 解构出roomId
    const { roomId } = req.query
    // 查询房间信息
    const info = await queryPromise(selectRoomInfoTableMaxSql, [
      parseInt(roomId)
    ])
    res.status(200).json({
      code: 200,
      msg: '获取信息成功',
      data: {
        info
      }
    })
  } catch (error) {
    console.log(error)
    res.status(500).json({ error: '获取失败' })
  }
})

// 根据时间段去查询聊天记录
roomRouter.get('/room/getRoomChatByTime', async (req, res) => {
  try {
    const { roomId, startTime, endTime } = req.query
    const chats = await queryPromise(selectRoomChatByTimeSql, [
      parseInt(roomId),
      startTime,
      endTime
    ])
    res.status(200).json({
      code: 200,
      msg: '获取信息成功',
      data: {
        chats
      }
    })
  } catch (error) {
    console.log(error)
    res.status(500).json({ error: '获取失败' })
  }
})

module.exports = roomRouter
